package com.blb.aop;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blb.entity.*;
import com.blb.mapper.LogMapper;
import com.blb.service.ICommodityService;
import com.blb.service.IGoodstypeService;
import com.blb.service.IOrderComService;
import com.blb.service.IOrdersService;
import com.blb.utils.IPUtils;
import com.blb.utils.UUIDUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Aspect
@Controller
public class AopTest {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private IOrderComService orderComService;

    @Autowired
    private IOrdersService ordersService;

    @Autowired
    private IGoodstypeService goodstypeService;

    @Autowired
    private ICommodityService commodityService;

    @Around("execution(* com.blb.controller.*.*(..))")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Log log = new Log();
        log.setId(UUIDUtils.getID());

        //获取用户对象
        Object object2 = request.getSession().getAttribute("user");
        if (object2 == null) {
            log.setUserid("");
            log.setUsername("");
        } else {
            User user = (User) object2;
            log.setUserid(user.getId());
            log.setUsername(user.getUsername());
        }
        log.setCreatetime(new Date());

        //获取ip
/*		InetAddress addr = InetAddress.getLocalHost();
		addr.getHostAddress();*/
        log.setIp(IPUtils.getIpAddr(request));


        //拼接method
        StringBuffer sb = new StringBuffer();
        sb.append(pjp.getSignature().getDeclaringTypeName());
        sb.append(".");
        sb.append(pjp.getSignature().getName());
        sb.append("(");
        Object[] args = pjp.getArgs();
        int i = 1;
        for (Object o : args) {
            sb.append(o);
            if (i == args.length) {
                break;
            }
            sb.append(",");
            i++;
        }
        sb.append(")");

        log.setMethod(sb.toString());

        log.setUrl(request.getRequestURI().toString());

        //向数据库添加
        logMapper.insert(log);

        Object object = pjp.proceed();

        return object;
    }

    /**
     * 看了本商品的人最终购买了
     * @param pjp
     */
    @Around("execution(* com.blb.controller.front.IndexController.goCommodityDetails(..))")
    public Object recommend(ProceedingJoinPoint pjp) throws Throwable {
        //访问目标方法的参数：
        Object[] args = pjp.getArgs();
        //该商品的ID
        String commodityId = (String)args[0];
        //当前用户
        FrontUser frontUser = (FrontUser) request.getSession().getAttribute("frontUser");

        //商品信息
        List<Commodity> commodityList = null;
        //通过当前商品id在订单商品表中查询购买该商品的所有订单
        List<OrderCom> orderComs = orderComService.list(new QueryWrapper<OrderCom>().eq("com_id", commodityId));
        //如果所有订单为空，则直接返回空
        if (orderComs.size()==0){
            request.setAttribute("commodityList",commodityList);
            Object object=pjp.proceed();
            return object;
        }
        List<String> orderids = new ArrayList<String>();
        for (OrderCom orderid : orderComs ){
            orderids.add(orderid.getOrderId());
        }
        //通过订单id在订单表中查询订单对应的用户id
        List<Orders> orders = ordersService.list(new QueryWrapper<Orders>().in("id", orderids));
        List<String> userids = new ArrayList<String>();
        for (Orders userid : orders){
            userids.add(userid.getUserId());
        }
        //根据用户id在订单表中查询订单的id
        orders = ordersService.list(new QueryWrapper<Orders>().in("user_id", userids));
        orderids = new ArrayList<String>();
        for (Orders orderid : orders){
            orderids.add(orderid.getId());
        }
        //根据订单id在订单商品表中查询商品id
        orderComs = orderComService.list(new QueryWrapper<OrderCom>().in("order_id", orderids));
        List<String> comids = new ArrayList<String>();
        for (OrderCom comid : orderComs){
            comids.add(comid.getComId());
        }

        //获取该商品的分类
        List<Goodstype> goodstype = goodstypeService.list(new QueryWrapper<Goodstype>().eq("com_id", commodityId));
        List<String> typeids = new ArrayList<String>();
        for (Goodstype typeid : goodstype){
            typeids.add(typeid.getTypeId());
        }

        //在商品分类表中查询这个分类下的，这些商品id下的商品id
        List<Goodstype> goodstypes = goodstypeService.list(new QueryWrapper<Goodstype>().in("type_id", typeids).in("com_id", comids));
        comids = new ArrayList<String>();
        for (Goodstype comid : goodstypes){
            comids.add(comid.getComId());
        }

        //根据商品id在商品信息表中查询商品信息
        commodityList = commodityService.list(new QueryWrapper<Commodity>().in("id", comids));
        for (Commodity commodity : commodityList){
            if (commodity!=null && commodity.getId().equals(commodityId)){
                commodityList.remove(commodity);
                break;
            }
        }
        request.setAttribute("commodityList",commodityList);

        Object object=pjp.proceed();
        return object;
    }

}
